/**
 * 中国9号健康产业有限公司
 * Copyright (C) JiuHaoHealth Corporation. All Rights Reserved
 */
package com.jiuhaohealth.log.launcher.weblistener;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.jiuhaohealth.log.launcher.conf.LauncherConfig;
import com.jiuhaohealth.log.launcher.handler.LogSocketClient;

/**
 * @author zhangguohua zhanggh@jiuhaohealth.com
 *
 *注册请求监听 监听所有请求
 *将header以及request body信息序列化成JSON
 *异步发送到指定服务
 */
public class LogLauncherListener implements ServletContextListener{
	// 当用户未在 web.xml 配置context-param logLauncherConfig时
	// 使用缺省配置
	private static final String DEFAULT_CONFIG_LOCATION="log-launcher.properties";
	
	public void contextInitialized(ServletContextEvent event) {
		LauncherConfig launcherConfig = LauncherConfig.getInstance();
		String configLocation = event.getServletContext().getInitParameter("logLauncherConfig");
		if(configLocation == null || "".equals(configLocation)){
			configLocation = LogLauncherListener.DEFAULT_CONFIG_LOCATION;
		}
		
		InputStream inputStream = getBasicConfIS(event,configLocation);
		if(inputStream != null){
			launcherConfig.initConfig(inputStream);
			
			//注册请求监听  
			//暂不启用自动监听
//			event.getServletContext().addListener(new LauncherRequestListener());
			
			//启动消费者进程
			LogSocketClient lsc = new LogSocketClient();
			launcherConfig.client = lsc;
			lsc.start();
		}else{
			launcherConfig.errorMsg("加载Log launcher配置文件失败，Log launcher程序未启动",null);
		}
		try {
			inputStream.close();
		} catch (IOException e1) {
			launcherConfig.errorMsg("关闭配置文件输入流异常", e1);
		}
	}
	
	private InputStream getBasicConfIS(ServletContextEvent event,String path){
		InputStream inputStream = event.getServletContext().getResourceAsStream("/WEB-INF/classes/"+path);
		try {
			inputStream.available();
		} catch (Exception e) {
			inputStream = null;
		}
		if(inputStream == null){
			ClassLoader classloader = Thread.currentThread().getContextClassLoader();
			inputStream = classloader.getResourceAsStream(path);
		}
		try {
			inputStream.available();
		} catch (Exception e) {
			inputStream = null;
		}
		
		return inputStream;
	}
	
	public void contextDestroyed(ServletContextEvent event) {
		// TODO Auto-generated method stub
	}
}
